<?php
class WeiBeeUser
{
	private $freedays = 5;
	public function ShowFirstLine()
	{
		$result = mysql_query("SELECT * FROM weibeeuser",$this->m_db);
		printf("User ID: %s<br>\n", mysql_result($result,0,"id"));
		printf("Last Visit: %s<br>\n", mysql_result($result,0,"lastlogin"));
	}
	private $m_db; 
    public function __construct() 
	{ 
        $this->m_db = mysql_connect("localhost", "y182319", "hao123"); 
		mysql_select_db("y182319",$this->m_db);
    }
	public function Insert($userid)
	{
		$insertCmd = "INSERT INTO weibeeuser values('" .$userid."',NOW(),".$this->freedays.")";
		$result = mysql_query($insertCmd,$this->m_db);
		return $result;
	}
	public function Query($userid)
	{
		$selectCmd = "SELECT * FROM weibeeuser where id=".$userid;
		$result = mysql_query($selectCmd,$this->m_db);
		$rs = mysql_fetch_array($result);
		return $rs;
	}
	public function UpdateDb($userid,$leftdays)
	{
		$updateCmd = "UPDATE weibeeuser SET daysleft=".$leftdays.",lastlogin=NOW() WHERE id=".$userid;
		$result = mysql_query($updateCmd,$this->m_db);
		return $result ;
	}
	public function GetWeiBeeInfo($userid)
	{
		$rs = $this->Query($userid);
		if( !$rs )
		{
			$this->Insert($userid);
			return $this->freedays;
		}
		list($year,$month,$day) = explode("-",date("Y-m-d",strtotime($rs["lastlogin"])));
		list($nyear,$nmonth,$nday) = explode("-",date("Y-m-d"));
		
		if( !(($year==$nyear) && ($month==$nmonth) && ($day==$nday)) )
		{
			$this->UpdateDb($userid,$rs["daysleft"]-1);
			return $rs["daysleft"]-1;
		}
		else
		{
			return $rs["daysleft"];
		}
	}
}
?>